package com.tuozixuan.javafx;

import javafx.event.EventHandler;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class EditingCell extends TableCell<Person, String> {

	private TextField textField;
	 
    public EditingCell() {            
    }

    @Override 
    public void startEdit() {
        super.startEdit();
        if (isEmpty()) {
            return;
        }

        if (textField == null) {
            createTextField();
        } else {
            textField.setText(getItem());
        }
        setGraphic(textField);
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    @Override         
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (!isEmpty()) {
            if (textField != null) {
                textField.setText(item);
            }
            setText(item);
        }
    }

    private void createTextField() {
        textField = new TextField(getItem());
        //textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        //textField.setMinWidth(this.getWidth());
        textField.setPrefWidth(this.getWidth());
        textField.setMaxHeight(this.getHeight() / 2);
        textField.setStyle("-fx-border-width: 0px;margin-top: 0px;");
        //textField.setBo
        textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override public void handle(KeyEvent t) {
                if (t.getCode() == KeyCode.ENTER) {
                    commitEdit(textField.getText());
                } else if (t.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                }
            }
        });
    }
}
